<template>
  <div class="ccc">
    <el-form ref="form" :model="form" label-width="80px">
      <div class="chaxun">
        <el-form-item label="广告标题" prop="advTitle">
          <el-input v-model="advTitle"></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="statusId">
          <el-select v-model="statusId" placeholder="请选择" clearable>
            <el-option label="禁用" value="0"></el-option>
            <el-option label="启用" value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button
            @click="getUserList"
            type="primary"
            icon="el-icon-search"
            class="jy"
            size="mini"
            >查询</el-button
          >

          <el-button class="jy" size="mini" @click="rest">
            <i class="el-icon-refresh"></i>
            重置</el-button
          >
          <el-button
            type="primary"
            icon="el-icon-circle-plus-outline"
            class="jy"
            size="mini"
            @click="toInsert"
            >添加</el-button
          >
        </el-form-item>
      </div>
    </el-form>
    <el-table
      :data="userList"
      border
      style="width: 100%"
      max-height="600"
      class="tab"
    >
      <el-table-column prop="id" label="序号" width="80" align="center">
      </el-table-column>
      <el-table-column prop="advImg" label="轮播图片" align="center">
        <template slot-scope="scope">
          <el-popover placement="right" trigger="hover">
            <img :src="scope.row.advImg" class="imgs" />
            <img
              slot="reference"
              :src="scope.row.advImg"
              style="max-height: 50px; max-width: 150px"
            />
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column prop="advTitle" label="广告标题" align="center">
      </el-table-column>
      <el-table-column prop="beginTime" label="开始时间" align="center">
      </el-table-column>
      <el-table-column prop="endTime" label="结束时间" align="center">
      </el-table-column>
      <el-table-column prop="statusId" label="状态" align="center">
        <template slot-scope="scope">
          <el-switch
            v-model.number="scope.row.statusId"
            active-color="#ff4949"
            inactive-color="#13ce66"
            :active-value="0"
            :inactive-value="1"
            active-text="禁用"
            inactive-text="启用"
            @change="updateStatus(scope.row.id, scope.row.statusId)"
          >
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column prop="sort" label="排序" width="80" align="center">
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template slot-scope="scope">
          <el-button
            type="primary"
            icon="el-icon-edit"
            :disabled="scope.row.statusId == 1 ? false : true"
            size="mini"
            @click="toUpdate(scope.row.id)"
            >修改</el-button
          >
          <el-button
            type="danger"
            icon="el-icon-delete"
            :disabled="scope.row.statusId == 1 ? false : true"
            size="mini"
            @click="del(scope.row.id)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="current"
      :page-sizes="[3, 4, 5, 6]"
      :page-size="size"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    >
    </el-pagination>
    <el-dialog
      :visible.sync="dialogVisible"
      width="30%"
      :before-close="handleClose"
      :title="flag"
    >
      <!-- 添加表单 -->
      <el-form ref="form" :model="form" label-width="80px">
        <el-form-item>
          <el-input v-model="form.id" v-if="false"></el-input>
        </el-form-item>
        <el-form-item label="轮播图" placeholder="advImg">
          <img :src="form.advImg" class="imgs" />
          <!-- 文件上传按钮 -->
          <el-button
            type="primary"
            icon="el-icon-upload"
            @click="imagecropperShow = true"
          >
          </el-button>
          <!--
                v-show：是否显示上传组件
                :key：类似于id，如果一个页面多个图片上传控件，可以做区分
                :url：后台上传的url地址
                @close：关闭上传组件
                @crop-upload-success：上传成功后的回调 -->
          <image-cropper
            v-show="imagecropperShow"
            :width="240"
            :height="120"
            :key="imagecropperKey"
            :url="'/oss/uploadImgFile'"
            field="file"
            @close="closeImage"
            @crop-upload-success="cropSuccess"
          />
        </el-form-item>
        <el-form-item label="轮播标题">
          <el-input
            v-model="form.advTitle"
            placeholder="输入轮播标题"
          ></el-input>
        </el-form-item>
        <el-form-item label="跳转链接">
          <el-input v-model="form.advUrl" placeholder="输入跳转链接"></el-input>
        </el-form-item>
        <el-form-item label="轮播顺序">
          <el-input-number
            v-model="form.sort"
            @change="handleChange"
            :min="1"
            :max="10"
            label="描述文字"
          ></el-input-number>
        </el-form-item>
        <!-- <el-form-item label="开始时间">
          <div class="block">
            <el-date-picker
              v-model="form.beginTime"
              format="yyyy-MM-dd HH:MM:SS"
              value-format="yyyy-MM-dd HH:MM:SS"
              type="datetime"
              placeholder="选择开始时间"
            >
            </el-date-picker>
          </div>
        </el-form-item>
        <el-form-item label="结束时间">
          <div class="block">
            <el-date-picker
              v-model="form.endTime"
              type="datetime"
              format="yyyy-MM-dd HH:MM:SS"
              value-format="yyyy-MM-dd HH:MM:SS"
              placeholder="选择结束时间"
            >
            </el-date-picker>
          </div>
        </el-form-item> -->
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="editUser">{{ flag }}</el-button>
      </span>
    </el-dialog>
  </div>
</template>


<script>
import {
  selectGetAll,
  updateStatus,
  getInsert,
  selectAllById,
  getUpdateById,
  getDeleteById,
} from "../../api/adv";
import ImageCropper from "../../components/ImageCropper";
import PanThumb from "../../components/PanThumb";
//添加组件
export default {
  components: { ImageCropper, PanThumb },
  data() {
    return {
      form: {
        id: "",
        advImg: "",
        advTitle: "",
        advUrl: "",
        advTarget: "",
        beginTime: "",
        endTime: "",
        sort: 1,
      },

      advTitle: "",
      statusId: "",
      //当前页码
      current: 1,
      //当前条数
      size: 5,
      //总条数
      total: 0,
      //男女单选组
      userList: [],
      //控制显示advAdd层的显示、
      dialogVisible: false,
      flag: "添加",

      imagecropperShow: false, // 是否显示上传组件
      imagecropperKey: 0, // 上传组件id
      field101Action: "https://jsonplaceholder.typicode.com/posts/",
      field101fileList: [],
    };
  },
  methods: {
    rest() {
      this.advTitle = null;
      this.statusId = null;
    },
    handleChange(sort) {
      console.log(sort);
    },
    //查询
    getUserList() {
      this.current = 1;
      this.findUserList();
    },
    async findUserList() {
      let result = await selectGetAll(
        this.current,
        this.size,
        this.advTitle,
        this.statusId
      );
      this.userList = result.data.pageList.records;
      this.total = result.data.pageList.total;
    },
    handleSizeChange(val) {
      this.size = val;
      this.findUserList();
    },
    handleCurrentChange(val) {
      this.current = val;
      this.findUserList();
    },
    async updateStatus(id, statusId) {
      let result = await updateStatus(id, statusId);
      console.log(result);
    },
    handleClose(done) {
      this.$confirm("确认关闭？")
        .then((_) => {
          this.form = {};
          this.dialogVisible = false;
          done();
        })
        .catch((_) => {});
    },
    del(id) {
      this.$confirm("确认删除？")
        .then((_) => {
          this.getDeleteById(id);
          done();
        })
        .catch((_) => {});
    },
    //新增
    async getInsert() {
      var $this = this;
      let result = await getInsert(this.form);
      if (result.data.code === 200) {
        //弹出消息
        $this.$message({
          message: "新增成功",
          type: "success",
          duration: 2000,
        });
        //关闭窗体
        $this.dialogVisible = false;
        //查询数据
        $this.findUserList();
        //清空数据
        $this.form = {};
      }
    },
    //修改
    async getUpdateById() {
      var $this = this;
      let result = await getUpdateById(this.form);
      if (result.data.code === 200) {
        //弹出消息
        $this.$message({
          message: "修改成功",
          type: "success",
          duration: 2000,
        });
        //关闭窗体
        $this.dialogVisible = false;
        //查询数据
        $this.findUserList();
        //清空数据
        $this.form = {};
      }
    },
    //删除
    async getDeleteById(id) {
      var $this = this;
      let result = await getDeleteById(id);
      if (result.data.code === 200) {
        //弹出消息
        $this.$message({
          message: "删除成功",
          type: "success",
          duration: 2000,
        });
        //查询数据
        $this.findUserList();
      }
    },
    async selectAllById(id) {
      let result = await selectAllById(id);
      this.form = result.data.adv;
    },
    editUser() {
      if (this.flag === "添加") {
        this.getInsert();
      } else {
        this.getUpdateById();
      }
    },
    toInsert() {
      (this.dialogVisible = true), (this.flag = "添加");
    },
    toUpdate(id) {
      (this.dialogVisible = true), (this.flag = "修改");
      //通过Id查询用户信息
      this.selectAllById(id);
    },
    field101BeforeUpload(file) {
      let isRightSize = file.size / 1024 / 1024 < 2;
      if (!isRightSize) {
        this.$message.error("文件大小超过 2MB");
      }
      let isAccept = new RegExp("image/*").test(file.type);
      if (!isAccept) {
        this.$message.error("应该选择image/*类型的文件");
      }
      return isRightSize && isAccept;
    },
    // 上传成功后的回调函数
    cropSuccess(data) {
      var oldImage = this.form.advImg;
      this.imagecropperShow = false;
      this.form.advImg = data.url;
      console.log(this.form.advImg);
      // 上传成功后，重新打开上传组件时初始化组件，否则显示上一次的上传结果
      this.imagecropperKey = this.imagecropperKey + 1;
      //上传成功之后删除之前的头像
      this.deleteAvatar(oldImage);
    },

    // 关闭上传组件
    closeImage() {
      this.imagecropperShow = false;
      // 上传失败后，重新打开上传组件时初始化组件，否则显示上一次的上传结果
      this.imagecropperKey = this.imagecropperKey + 1;
    },
    //删除上传之前的图片
    async deleteAvatar(oldImage) {
      const { data } = await deleteImgFile(oldImage);
    },
  },
  created() {
    //获取轮播图信息
    this.findUserList();
  },
};
</script>

<style lang="less" scoped>
.el-input {
  width: 200px;
  height: 30px;
}

.chaxun {
  display: flex;
}
.el-select {
  width: 120px;
}
.jy {
  height: 30px;
  margin-left: 20px;
}
.imgs {
  width: 300px;
  height: 150px;
}
</style>